package com.jiagoushi.cloud.study.user.controller;

import com.jiagoushi.cloud.study.user.entity.User;
import com.jiagoushi.cloud.study.user.feign.UserFeignClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

/**
 * 演示 user服务挂了超时和执行请求超时
 */
@RestController
public class OrderController {
  private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

  @Autowired
  private UserFeignClient userFeignClient;

  @Autowired
  private RestTemplate restTemplate;

  /**
   * Hystrix调用接口默认1秒超时，超时后会自动执行降级方法,可在文件配置，配置文件配置是全局的，
   * @HystrixCommand(fallbackMethod = "findByIdFallback") 注解也可以配置超时
   */
  @HystrixCommand(fallbackMethod = "findByIdFallback") // 基于注解的hystrix 推荐使用
  @GetMapping("/user/{id}")
  public User findById(@PathVariable Long id) {
	logger.info("================请求用户中心接口==============");
    return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
    //return userFeignClient.findById2(id);
  }

  // 降级的方法
  public User findByIdFallback(Long id) { 
    User user = new User();
    user.setId(-1L);
    user.setName("降级用户");
    return user;
  }

}
